package com.ywd.materials.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ywd.materials.admin.constants.JwtConstant;
import com.ywd.materials.admin.constants.RedisPrefixConstants;
import com.ywd.materials.admin.context.UserContext;
import com.ywd.materials.admin.dto.AdminUserDto;
import com.ywd.materials.admin.dto.AdminUserLoginDto;
import com.ywd.materials.admin.dto.AdminUserUpdateDto;
import com.ywd.materials.admin.dto.query.UserPageQuery;
import com.ywd.materials.admin.entity.AdminRoleEntity;
import com.ywd.materials.admin.entity.MaterialsWarehouseEntity;
import com.ywd.materials.admin.entity.MaterialsWarehouseUserEntity;
import com.ywd.materials.admin.entity.AdminUserEntity;
import com.ywd.materials.admin.exception.CommonException;
import com.ywd.materials.admin.exception.EmError;
import com.ywd.materials.admin.exception.RPage;
import com.ywd.materials.admin.mapper.AdminUserMapper;
import com.ywd.materials.admin.utils.JwtTokenUtil;
import com.ywd.materials.admin.utils.PasswordEncoderUtil;
import com.ywd.materials.admin.utils.RedisUtil;
import com.ywd.materials.admin.vo.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * YWD
 * 2025/11/10
 */
@AllArgsConstructor
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUserEntity> {

    private final RedisUtil redisUtil;
    private final AdminRoleServiceImpl adminRoleServiceImpl;
    private final AdminMenuServiceImpl adminMenuServiceImpl;


    public String login(AdminUserLoginDto dto) {
        LambdaQueryWrapper<AdminUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUserEntity::getUserName, dto.getUserName())
                .eq(AdminUserEntity::getIsDeleted, 0);
        AdminUserEntity adminUserEntity = this.baseMapper.selectOne(queryWrapper);
        //用户
        if (ObjectUtil.isEmpty(adminUserEntity)) {
            throw new CommonException(EmError.AUTH_USER_IS_NULL);
        }
        //解密和校验密码
        boolean matches = PasswordEncoderUtil.matches(dto.getPassword(), adminUserEntity.getPassword());
        if (!matches) {
            throw new CommonException(EmError.AUTH_PASSWORD_ERROR);
        }
        //构建返回对象
        AdminUserVo adminUserVo = new AdminUserVo();
        BeanUtils.copyProperties(adminUserEntity, adminUserVo);
        //角色信息
        AdminRoleEntity roleEntity = adminRoleServiceImpl.getById(adminUserVo.getRoleId());
        adminUserVo.setRoleName(roleEntity.getName());
        AdminUserDetailsVo adminUserDetailsVo = new AdminUserDetailsVo();
        adminUserDetailsVo.setUserVo(adminUserVo);
//        //菜单信息
//        List<AdminMenuTreeVo> treeVoList = adminMenuServiceImpl.getByRoleId(adminUserVo.getRoleId());
//        if (CollectionUtil.isNotEmpty(treeVoList)) {
//            adminUserDetailsVo.setMenuTreeVoList(treeVoList);
//        }
        long expireTime = JwtConstant.EXPIRATION_REMEMBER;
        // 生成JwtToken
        String token = JwtTokenUtil.createToken(adminUserVo.getId().toString(), expireTime * 1000L);
        adminUserVo.setToken(token);
        // 存入Redis，如果缓存时间更长就使用缓存时间
        Long redisExpireTime = redisUtil.getExpire(RedisPrefixConstants.MATERIALS_ADMIN_USER_INFO + adminUserVo.getId());
        if (Objects.nonNull(redisExpireTime) && redisExpireTime > expireTime) {
            expireTime = redisExpireTime;
        }
        //缓存
        redisUtil.setObject(RedisPrefixConstants.MATERIALS_ADMIN_USER_INFO + adminUserVo.getId(), adminUserDetailsVo, expireTime);
        UserContext.setUser(adminUserDetailsVo);
        //更新登录状态
        adminUserEntity.setStatus(1);
        updateById(adminUserEntity);
        return token;
    }

    public Boolean out() {
        AdminUserDetailsVo userVo = UserContext.getUser();
        AdminUserVo user = userVo.getUserVo();
        LambdaUpdateWrapper<AdminUserEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdminUserEntity::getId, user.getId())
                .set(AdminUserEntity::getStatus, 0);
        this.update(updateWrapper);
        //清除缓存
        redisUtil.deleteKey(RedisPrefixConstants.MATERIALS_ADMIN_USER_INFO + user.getId());
        UserContext.clearUser();
        return true;
    }

    public Boolean updatePassword(AdminUserUpdateDto dto) {
        AdminUserDetailsVo userVo = UserContext.getUser();
        AdminUserVo user = userVo.getUserVo();
        LambdaQueryWrapper<AdminUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUserEntity::getUserName, user.getUserName())
                .eq(AdminUserEntity::getIsDeleted, 0);
        AdminUserEntity adminUserEntity = baseMapper.selectOne(queryWrapper);
        //判断旧密码是否匹配
        boolean matches = PasswordEncoderUtil.matches(dto.getPassword(), adminUserEntity.getPassword());
        if (!matches) throw new CommonException("原密码错误");
        adminUserEntity.setPassword(PasswordEncoderUtil.encode(dto.getNewPassword()));
        //更新密码
        this.updateById(adminUserEntity);
        //清除缓存
        redisUtil.deleteKey(RedisPrefixConstants.MATERIALS_ADMIN_USER_INFO + user.getId());
        UserContext.clearUser();
        return true;
    }

    public AdminUserDetailsVo getUserInfo() {
        AdminUserDetailsVo userVo = UserContext.getUser();
        AdminUserVo user = userVo.getUserVo();
        //菜单信息
        List<AdminMenuTreeVo> treeVoList = adminMenuServiceImpl.getByRoleId(user.getRoleId());
        if (CollectionUtil.isNotEmpty(treeVoList)) {
            userVo.setMenuTreeVoList(treeVoList);
        }
        return userVo;
    }

    public RPage<List<AdminUserVo>> getUserPage(UserPageQuery query) {
        final Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<AdminUserVo> list = this.baseMapper.getUserPage(query);
        return RPage.ok(list, query.getPage(), query.getLimit(), page.getTotal());
    }

    public AdminUserVo getUserDetails(Long id) {
        return this.baseMapper.getUserDetails(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean saveUser(AdminUserDto dto) {
        if (ObjectUtil.isEmpty(dto.getRoleId())) throw new CommonException("未指定用户角色");
        //新增用户
        return this.save(BeanUtil.copyProperties(dto, AdminUserEntity.class));
    }

    public Boolean updateUser(AdminUserDto dto) {
        if (ObjectUtil.isEmpty(dto.getRoleId())) throw new CommonException("未指定用户角色");
        return updateById(BeanUtil.copyProperties(dto, AdminUserEntity.class));
    }

    public Boolean deleteUser(Long id) {
        if (id.equals(1L)) throw new CommonException("该用户不能删除");
        return removeById(id);
    }


}
